package com.xhdx.threadpool.tools;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号灯：当线程空闲时自动去执行阻塞的线程，实现运行最优化
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        // 定义信号灯，一次最多能处理3个线程
        Semaphore sp = new Semaphore(3);
        for (int i = 0; i < 20; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 获取信号，信号灯处理阻塞线程，最多允许3个线程访问
                        sp.acquire();
                        System.out.println(
                                Thread.currentThread().getName() + ":进入信号灯，还有" + sp.availablePermits() + "个信号");

                        Thread.sleep(new Random().nextInt(2000));

                        // 回收信号灯信号，供别的线程使用
                        sp.release();
                        System.out.println(
                                Thread.currentThread().getName() + ":离开信号灯，还有" + sp.availablePermits() + "个信号");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}